import json
import argparse

# Read and parse the JSON file
def read_json_file(file_path):
    with open(file_path, 'r') as file:
        data = [json.loads(line.strip()) for line in file if line.strip()]
    return data

# Calculate the time delay and store the result
def calculate_time_diffs(data):
    results = {
        'Q2G': [],
        'G2I': [],
        'Q2M': [],
        'I2D': [],
        'M2D': [],
        'D2C': [],
        'Q2C': []
    }
    for item in data:
        event = item['event']
        if event == 'G' and item['blk_qts'] != 0 and item['blk_gts'] != 0:
            results['Q2G'].append(item['blk_gts'] - item['blk_qts'])
        elif event == 'I' and item['blk_gts'] != 0 and item['blk_its'] != 0:
            results['G2I'].append(item['blk_its'] - item['blk_gts'])
        elif event == 'M' and item['blk_qts'] != 0 and item['blk_mts'] != 0:
            results['Q2M'].append(item['blk_mts'] - item['blk_qts'])
        elif event == 'D' and item['blk_its'] != 0 and item['blk_dts'] != 0:
            results['I2D'].append(item['blk_dts'] - item['blk_its'])
            if item['blk_mts'] != 0:  
                results['M2D'].append(item['blk_dts'] - item['blk_mts'])
        elif event == 'C' and item['blk_dts'] != 0 and item['blk_cts'] != 0:
            results['D2C'].append(item['blk_cts'] - item['blk_dts'])
            if item['blk_qts'] != 0:  
                results['Q2C'].append(item['blk_cts'] - item['blk_qts'])

    return results

# Collect statistical information
def calculate_stats(results):
    stats = {}
    for key, values in results.items():
        stats[key] = {
            'min': min(values) if values else 0,
            'max': max(values) if values else 0,
            'average': sum(values) / len(values) if values else 0,
            'count': len(values)
        }
    return stats

def main():
    parser = argparse.ArgumentParser(description="Calculate time differences from a JSON file.")
    parser.add_argument('-i', '--input', dest='file_path', required=True, help='Path to the input JSON file')
    args = parser.parse_args()
    data = read_json_file(args.file_path)
    time_diffs = calculate_time_diffs(data)
    stats = calculate_stats(time_diffs)
    for event_type, values in stats.items():
        print(f"{event_type}:")
        print(f"  Min: {values['min']}")
        print(f"  Max: {values['max']}")
        print(f"  Avg: {values['average']:.4f}")  
        print(f"  Count: {values['count']}")
        print()  

if __name__ == '__main__':
    main()